import { Controller, Post, Get, Inject, Body, Query } from '@midwayjs/core';
import { FeedService } from '../service/feed.service';
import {
  ApiTags,
  ApiOperation,
  ApiBody,
  ApiResponse,
  ApiProperty,
} from '@midwayjs/swagger';
import { Validate, Rule, RuleType } from '@midwayjs/validate';

class PublishDto {
  @ApiProperty({ description: '发布者用户ID', example: 1, minimum: 1 })
  @Rule(RuleType.number().integer().min(1).required())
  userId: number;

  @ApiProperty({
    description: '文本内容',
    example: '今天心情不错',
    minLength: 1,
    maxLength: 2000,
  })
  @Rule(RuleType.string().min(1).max(2000).required())
  content: string;

  @ApiProperty({
    description: '图片地址（单张）',
    example: 'https://example.com/1.jpg',
  })
  @Rule(RuleType.string().uri().required())
  imageUrl: string;
}

class ListQueryDto {
  @ApiProperty({
    description: '用户ID（可选，按作者过滤）',
    required: false,
    example: 1,
  })
  @Rule(RuleType.number().integer().min(1).optional())
  userId?: number;

  @ApiProperty({ description: '页码，从1开始', example: 1, minimum: 1 })
  @Rule(RuleType.number().integer().min(1).required())
  page: number;

  @ApiProperty({
    description: '每页条数',
    example: 20,
    minimum: 1,
    maximum: 100,
  })
  @Rule(RuleType.number().integer().min(1).max(100).required())
  pageSize: number;
}

class ReadDto {
  @Rule(RuleType.number().integer().min(1).required())
  id: number;
}

@ApiTags(['Feed'])
@Controller('/api/feed')
export class FeedController {
  @Inject()
  feedService: FeedService;

  @ApiOperation({ summary: '发布动态' })
  @ApiBody({
    description: '发布参数',
    type: PublishDto,
    examples: {
      default: {
        value: {
          userId: 1,
          content: '今天心情不错',
          imageUrl: 'https://example.com/1.jpg',
        },
      },
    },
  })
  @ApiResponse({ status: 200, description: '发布成功' })
  @Post('/publish')
  @Validate()
  async publish(@Body() body: PublishDto) {
    const ret = await this.feedService.publish(
      BigInt(body.userId),
      body.content,
      body.imageUrl
    );
    return { success: true, data: ret };
  }

  @ApiOperation({ summary: '动态列表' })
  @ApiResponse({ status: 200, description: '列表成功' })
  @Get('/list')
  @Validate()
  async list(@Query() query: ListQueryDto) {
    const page = Number(query.page || 1);
    const pageSize = Number(query.pageSize || 20);
    const userId = query.userId ? BigInt(query.userId) : undefined;
    const data = await this.feedService.list({ userId, page, pageSize });
    return { success: true, data };
  }

  @ApiOperation({ summary: '阅读数+1' })
  @ApiBody({
    description: '阅读计数参数',
    schema: {
      type: 'object',
      properties: { id: { type: 'integer', example: 1 } },
      required: ['id'],
    },
    examples: { default: { value: { id: 1 } } },
  })
  @Post('/read')
  @Validate()
  async read(@Body() body: ReadDto) {
    const ret = await this.feedService.incrementRead(BigInt(body.id));
    return { success: true, data: ret };
  }
}
